#!/usr/bin/env bash

SELFDIR=$(cd $(dirname "$0");pwd)

if [[ ${PYTHON} == "" ]]; then
    PYTHON=python3
fi

python_version=$(${PYTHON} --version)
if [[ ! "${python_version}" =~ ^Python[[:space:]]+3\.[0-9]+\.[0-9]+ ]]; then
    echo    "Unsupported python version: ${python_version}"
    exit    1
fi


function show_help()
{
    echo    "Usage:"
    echo    "   rcgen <TEMPL-NAME> <OUTPUT-DIR> <PARAM-FILE>"
    echo    ""
    echo    "Examples:"
    echo    "   rcgen 'shell/objc' sample.xml ./tmp"

    return  0
}


#   $1  tmpla_name
#   $2  param_file
#   $3  output_dir
function gen_one_file()
{
    local tmpla_name="$1"
    local param_file="$2"
    local output_dir="$3"

    #   从模板目录下找到所有的模板文件
    local all_files=$(cd "${SELFDIR}/templates/${tmpla_name}" && find . -name 'T@*')

    #   逐个文件替换：需要注意文件名也是需要替换的
    for file in ${all_files} ; do
        #   对参数文件执行字符串替换，生成真实文件名
        local realname=$(${PYTHON} "${SELFDIR}/jsontmpl.py" -s $(echo "${file}" | sed 's#T@##g') -p "${params_file}")
        if [[ ${realname} == "" ]]; then
            echo    "Can not replace the template file name: '${file}'"
            return  1
        fi

        #   先尝试清理掉老的文件
        rm -rf "${output_dir}/${realname}"

        #   如果目标文件所在的目录不存在，尝试创建一下全部目录
        mkdir -p $(dirname "${output_dir}/${realname}")

        #   启动模板替换脚本
        ${PYTHON} "${SELFDIR}/jsontmpl.py" -f "${SELFDIR}/templates/${tmpla_name}/${file}" -p "${params_file}" -o "${output_dir}/${realname}"
        RESULT=$?
        if [[ ${RESULT} -ne 0 ]]; then
            echo    "[Fail] ${tmpla_name}/${file} -> ${output_dir}/${realname}"
            return  1
        else
            echo    "[ OK ] ${tmpla_name}/${file} -> ${output_dir}/${realname}"
            continue
        fi
    done

    return  0
}


function main()
{
    #   显示帮助
    if [[ "$1" == "-h" || "$1" == "--help" ]]; then
        show_help   "$@"
        return      "$?"
    fi

    #   参数个数检查
    if [[ $# -lt 3 ]]; then
        echo    "Missing parameters, type -h for help"
        return  1
    fi

    #   检查一下指定的模板是否存在
    local tmpla_name="$1"
    if [[ ! -d "${SELFDIR}/templates/${tmpla_name}" ]]; then
        echo    "Can not found the template named '${tmpla_name}'"
        return  1
    fi

    if [[ ! -f "${SELFDIR}/templates/${tmpla_name}/.rcgen" ]]; then
        echo    "The .rcgen file is missing under the template directory: '${SELFDIR}/templates/${tmpla_name}/.rcgen'"
        return  1
    fi

    export RCGEN_HOME=${SELFDIR}
    export COMPILER=""
    source "${SELFDIR}/templates/${tmpla_name}/.rcgen"
    if [[ : = "" ]]; then
        echo    "The COMPILER parameter is not defined in the .rcgen file: '${SELFDIR}/templates/${tmpla_name}/.rcgen'"
        return  1
    fi

    if [[ ! -f "${COMPILER}" = "" ]]; then
        echo    "The COMPILER is missing: '${COMPILER}'"
        return  1
    fi

    #   创建输出目录
    local output_dir="$2"
    if [[ ! -d "${output_dir}" ]]; then
        mkdir -p "${output_dir}"
        if [[ ! -d "${output_dir}" ]]; then
            echo    "Can not recreate the output dir: '${output_dir}'"
            return  1
        fi
    fi

    #   检查参数文件
    local params_file="$3"
    if [[ ! -f "${params_file}" ]]; then
        echo    "Can not found the parameters file: '${params_file}'"
        return  1
    fi

    #   执行编译生成文件清单
    local list_file_name="${output_dir}/$(basebane "${params_file}").list"
    rm -rf "${list_file_name}"
    ${PYTHON} "${COMPILER}" "${params_file}" -o "${output_dir}" -l "${list_file_name}"
    RESULT=$?
    if [[ ${RESULT} -ne 0 ]]; then
        echo    "Generate json parameter file faile: '${params_file}' -> '${params_file}.json'"
        return  1
    fi

    #   对清单上的文件逐个执行渲染
    local json_files=$(cat "${list_file_name}")
    for json_file in ${json_files} ; do
        gen_one_file "${tmpla_name}" "${json_file}" "${output_dir}"
    done

    return  0
}

main    "$@"
exit    "$?"

